import 'dart:async';

import 'package:awesome_project/pages/main_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:go_router/go_router.dart';

import 'package:awesome_project/pages/area_list_page.dart'
    deferred as area_list_page;

import 'package:mpflutter_core/mpflutter_core.dart';

late GoRouter appRouter;

///search_page删除跳转
class RoutePath {
  RoutePath._();

  static const String main = '/';
  static const String areaListPage = '/areaListPage';

  static const List<String> needLoginPages = [];
}

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

Future<void> initRouter() async {
  await area_list_page.loadLibrary();
  final GoRouter goRouter = GoRouter(
      navigatorKey: navigatorKey,
      /**
       * 务必保留 MPNavigatorObserver，否则小程序的路由会出问题。
       */
      observers: [MPNavigatorObserver(), FlutterSmartDialog.observer],
      routes: [
        GoRoute(
            path: RoutePath.main,
            builder: (context, state) {
              return const MainPage();
            }),
        GoRoute(
            path: RoutePath.areaListPage,
            builder: (context, state) {
              return area_list_page.AreaListPage();
            }),
      ],
      redirect: (context, state) async {},
      debugLogDiagnostics: true,
      initialLocation: RoutePath.main);
  appRouter = goRouter;
}

extension GoRouterX on GoRouter {
  Future<T?> pushAndRemoveUntilX<T extends Object?>(
      String location, String popUtil,
      {Object? extra}) {
    routerDelegate.navigatorKey.currentState
        ?.popUntil(ModalRoute.withName(popUtil));
    return push(location, extra: extra);
  }

  //
  void popUntil(String location) {
    routerDelegate.navigatorKey.currentState
        ?.popUntil(ModalRoute.withName(location));
  }

  void singTopPush(String location, {Object? extra}) {
    pushReplacement(location, extra: extra);
  }
}
